<?php



class Products_Home_Controller extends Base_Controller {

	public $restful = true;
	public $USER;
	public $POSTID;

	public function __construct()
	{
		parent::__construct();
		//--Your Code --//
		$this->USER = Auth::user();

		$this->theme->set_theme("default");
		$this->theme->set_layout("member");
	}


	public function get_all($post_id){
		if (Auth::guest()) return Redirect::to('login');
		$this->theme->set_layout("member");

		//--BREADCRUMB--//
		Breadcrumb::addbreadcrumb('Home', URL::base());
		Breadcrumb::addbreadcrumb(' Product', URL::base().'/product');
		Breadcrumb::setSeparator('&raquo;');
		$data['breadcrumb'] = Breadcrumb::generate();

		//--DATA--//
		$data['title'] = "All Products";
		$data['post'] = Post::find($post_id);
		$data['products'] = Products::where('post_id', '=', $post_id)
		->get();

		$this->theme->title($data['title'].' - '.Settings::get('en','site_title'));

		return $this->theme->render('products::index', $data);
	}

	public function get_add($post_id){

		if (Auth::guest()) return Redirect::to('login');
		$this->theme->set_layout("member");

		//--BREADCRUMB--//
		Breadcrumb::addbreadcrumb('Home', URL::base());
		Breadcrumb::addbreadcrumb(' Product', URL::base().'/product');
		Breadcrumb::addbreadcrumb('Add New', URL::base().'/product/add');
		Breadcrumb::setSeparator('&raquo;');
		$data['breadcrumb'] = Breadcrumb::generate();

		//--DATA--//
		$data['title'] = "Add Products";

		$this->theme->title($data['title'].' - '.Settings::get('en','site_title'));

		$data['post'] = Post::find($post_id);

		$data['cat_parent'] = Categories::where('parent_id','=',0)->select(array('id', 'name'))->get();

		return $this->theme->render('products::create', $data);
	}

	public function post_add($post_id){
		if (Auth::guest()) return Redirect::to('login');

		$rules = array(
				'title' => 'required|min:1',
				'description' => 'required|min:10',
				'price' => 'required|min:2',
				'category' => 'required'
		);
		$validator = Validator::make(Input::get(), $rules);
		if( $validator->fails() )
		{
			return Redirect::back()->with_input()->with_errors($validator)->with('message','Invalid Operation !');
		}else{

			$filename = Input::file('image.name');

			//dd($filename);

			$extension = File::extension($filename);
			$image = Input::file('image');
			$dirPath = path('storage').'uploads/products/';
			$filename = $image['name'];

			if($filename == FALSE){
				return Redirect::back()->with('message','<div class="alert alert-warning">Browse filed can not be null..</div>');
			}

			$createFolders = true;
			$backgroundColor = null;
			$imageQuality = 100;

			//--NEW NAME --//
			$filename = md5($filename).'.'.$extension;

			$layer = PHPImageWorkshop\ImageWorkshop::initFromPath($image['tmp_name']);

			$thumbWidth = 300; // px
			$thumbHeight = 250;
			$conserveProportion = false;
			$positionX = 0; // px
			$positionY = 0; // px
			$position = 'LT';

			$layer->resizeInPixel($thumbWidth, $thumbHeight, $conserveProportion, $positionX, $positionY, $position);
			$layer->save($dirPath, $filename, $createFolders, $backgroundColor, $imageQuality);



			$post_data = array(
					'post_id' => $post_id,
					'title' => Input::get('title'),
					'category' => Input::get('category'),
					'slug' => Str::slug(Input::get('title')),
					'image' => $filename,
					'description' => Input::get('description'),
					'price' => Input::get('price'),
			);

			DB::table('products')->insert($post_data);



			//dd($post_data);

			return Redirect::back()->with('message','Data Successfully added!');
		}
	}


	public function get_edit($pID){
			
			
		if (Auth::guest()) return Redirect::to('login');
		$this->theme->set_layout("member");
			
		
		
		//--DATA--//
		$data['title'] = "Edit Products";
		$data['product'] = Products::where('id','=',$pID)->first();
		
		//--Meta Title--//
		
		$this->theme->title('Edit Product'.' - '.$data['product']->title.' - '.Settings::get('en','site_title'));
		
		//--BREADCRUMB--//
		Breadcrumb::addbreadcrumb('Home', URL::base());
		Breadcrumb::addbreadcrumb($data['title'], URL::base().'/product');
		Breadcrumb::setSeparator('&raquo;');
		$data['breadcrumb'] = Breadcrumb::generate();
			
		
		return $this->theme->render('products::edit', $data);
			
	}

	public function post_edit(){
			
		if (Auth::guest()) return Redirect::to('login');
			
		$rules = array(
				'title' => 'required|min:1',
				'description' => 'required|min:10',
				'price' => 'required|min:2',
		);
		$validator = Validator::make(Input::get(), $rules);
			
		$thisOrderid = Input::get('pID');
			
		if( $validator->fails() )
		{
			return Redirect::back()->with_input()->with_errors($validator)->with('message','Invalid Operation !');
		}else{

			$filename = Input::file('image.name');

			if($filename == TRUE){

				//dd($filename);
					
				$extension = File::extension($filename);
				$image = Input::file('image');
				$dirPath = path('storage').'uploads/products/';
				$filename = $image['name'];
					

				$createFolders = true;
				$backgroundColor = null;
				$imageQuality = 100;
					
				//--NEW NAME --//
				$filename = md5($filename).'.'.$extension;
					
				$layer = PHPImageWorkshop\ImageWorkshop::initFromPath($image['tmp_name']);
					
				$thumbWidth = 300; // px
				$thumbHeight = 250;
				$conserveProportion = false;
				$positionX = 0; // px
				$positionY = 0; // px
				$position = 'LT';
					
				$layer->resizeInPixel($thumbWidth, $thumbHeight, $conserveProportion, $positionX, $positionY, $position);
				$layer->save($dirPath, $filename, $createFolders, $backgroundColor, $imageQuality);
					
				
				if(Input::get('category')){
					$cat = Input::get('category');
				}if(Input::get('cat')){
					$cat = Input::get('cat');
				}
				
				
				
				

				$post_data = array(
						'post_id' => Input::get('postID'),
						'category' => $cat,
						'title' => Input::get('title'),
						'slug' => Str::slug(Input::get('title')),
						'image' => $filename,
						'description' => Input::get('description'),
						'price' => Input::get('price'),
				);



				$image_file = Products::where('id','=',$thisOrderid)->first();
				$path = path('storage').'uploads/products/'.$image_file->image;

				//	dd($path);
				File::delete($path);


				DB::table('products')->where('id','=',$thisOrderid)->update($post_data);
			}else{
				
				
				if(Input::get('category')){
					$cat = Input::get('category');
				}if(Input::get('cat')){
					$cat = Input::get('cat');
				}
				
				
					
				$post_data = array(
						'post_id' => Input::get('postID'),
						'category' => $cat,
						'title' => Input::get('title'),
						'slug' => Str::slug(Input::get('title')),
						'description' => Input::get('description'),
						'price' => Input::get('price'),
				);
					
				DB::table('products')->where('id','=',$thisOrderid)->update($post_data);
			}

			return Redirect::back()->with('message','Data Successfully updated!');
		}
			
	}

	public function get_delete($pID,$image){


		Products::where('id','=',$pID)->delete();
		$path = path('storage').'uploads/products/'.$image;
		File::delete($path);
		return Redirect::back();

	}


	public function post_products(){

		$term = (int) Input::get('selectbox-3');

		$offset = 0 ; $limit = 10;

		$PID = Hierarchy::get_descendents('categories', $term);

		if($PID){
				
			foreach($PID as $PID){

				$PID = $PID->lineage;

			}
			
			$cID = explode('-',$PID);



			$gSQL='';
			for($i=0; $i < count($cID); $i++){
				$gSQL .= "C.id = ".$cID[$i]." OR ";
			}

			$len=strlen($gSQL);
			$pos=strrpos($gSQL, 'OR');
			$gSQL= substr($gSQL,0,$pos);



			$sql = "SELECT P.* FROM products AS P
			INNER JOIN categories AS C ON P.category = C.id WHERE ($gSQL)
			limit $offset,$limit";
				
		}else{

			$sql = "SELECT P.* FROM products AS P
			INNER JOIN categories AS C ON P.category = C.id WHERE C.id = '$term'
			limit $offset,$limit";

		}

		$result = DB::query($sql);

		$product = Categories::find($term)->slug;

	//	dd($product);
		return Redirect::to ('products'.'/'.$product);

	}


	public function get_product($product){
			

		$data['mode'] = "PRODUCTS";
		$offset = 0 ; $limit = 10;

		$title = Categories::where('slug','=',$product)->first();

		
		
		$data['title'] = $title->name;
		
		$PID = Categories::where('slug','=',$product)->first();
		
		$cID = $PID->id;
		
		$PID = Hierarchy::get_descendents('categories', $PID->id);
		
		
		if($PID){
				
			foreach($PID as $PID){

				$PID = $PID->lineage;

			}
			
			$cID = explode('-',$PID);


			

			$gSQL='';
			for($i=0; $i < count($cID); $i++){
				$gSQL .= $cID[$i].",";
			}

			$len=strlen($gSQL);
			$pos=strrpos($gSQL, ',');
			$gSQL= substr($gSQL,0,$pos);



			$sql = "SELECT P.* FROM products AS P
			INNER JOIN categories AS C ON P.category = C.id WHERE C.id in ($gSQL)
			limit $offset,$limit";
				
		}else{

			$sql = "SELECT P.* FROM products AS P
			INNER JOIN categories AS C ON P.category = C.id WHERE C.id = '$cID'
			limit $offset,$limit";

		}

		
		$result = DB::query($sql);
		
		$data['products'] = $result;

		//--Meta Title--//
		
		$this->theme->title('Products'.' in '.$data['title'].' - '.Settings::get('en','site_title'));

		//--BREADCRUMB--//
		Breadcrumb::addbreadcrumb('Home', URL::base());
		Breadcrumb::addbreadcrumb($data['title'], URL::base());
		Breadcrumb::setSeparator('&raquo;');
		$data['breadcrumb'] = Breadcrumb::generate();

		$this->theme->set_theme("default");
		$this->theme->set_layout("column3");

		return $this->theme->render('products::products',$data);
			
	}


	public function post_requirements(){

		$term = (int) Input::get('requirement');
		$location = (int) Input::get('requirement_location');




		//$loc =  Cookie::get('location_cookie');
		$loc = Input::get('loc');
		
		$locname = Locations::where('slug','=',$loc)->first();
		if($locname){
			$loc = $locname->id ;
		
		}else{
			$loc = '';
		}

		$offset = 0 ; $limit = 10;



		if($location){

			$sql = "SELECT P.* FROM postrequirement AS P
			INNER JOIN categories AS C ON P.category = C.id AND C.id= '$term'
			INNER JOIN locations AS L ON P.location = L.id WHERE L.id= '$location' limit $offset,$limit
			";


		}if($loc){

			$sql = "SELECT P.* FROM postrequirement AS P
			INNER JOIN categories AS C ON P.category = C.id AND C.id= '$term'
			INNER JOIN locations AS L ON P.location = L.id WHERE L.id= '$loc' limit $offset,$limit
			";


		}

		if(!$location && !$loc){

			$sql = "Select * from postrequirement where category= '$term' ";

		}

		$result = DB::query($sql);

		$postrequirement = Categories::find($term)->slug;


		if(($location) ){
			$inputloc = Locations::find($location)->slug;
			Location::set($location);
			return Redirect::to ('products/buylead'.'/'.$inputloc.'/'.$postrequirement);
		}if($loc){
			$sesloca = $locname->slug;
			
			Location::set($loc);
			return Redirect::to ('products/buylead'.'/'.$sesloca.'/'.$postrequirement);
		}if(!$location && !$loc){
			$notloation = Settings::get('en','default_location');
			Location::set(Settings::get('en','default_location'));
			return Redirect::to ('products/buylead'.'/'.$notloation.'/'.$postrequirement);
		}

		//return Redirect::to ('buylead'.'/'.$postrequirement);

	}

	public function get_buylead($locan,$postreq){



		$loca = $this->SlugID('locations',$locan);
		
		
		$postrequirement = Categories::where('slug','=',$postreq)->first();
		$term = $postrequirement->id;

		$data['category'] = Categories::where('slug','=',$postreq)->first();

		$offset = 0 ; $limit = 10;

		if($loca){

			$sql = "SELECT P.* FROM postrequirement AS P
			INNER JOIN categories AS C ON P.category = C.id AND C.id= '$term'
			INNER JOIN locations AS L ON P.location = L.id WHERE L.id= '$loca' limit $offset,$limit
			";


		}
		if(!$loca){
			$sql = "Select * from postrequirement where category= '$term' ";
		}

		$result = DB::query($sql);


		$data['mode'] = "LEAD";
		$data['requirements'] = $result;


		//--Meta Title--//
		
		$this->theme->title('Products'.' | Buy Lead in '.$data['category']->name.' - '.Settings::get('en','site_title'));
		
		//--BREADCRUMB--//
		Breadcrumb::addbreadcrumb('Home', URL::base());
		Breadcrumb::addbreadcrumb('as', URL::base());
		Breadcrumb::setSeparator('&raquo;');
		$data['breadcrumb'] = Breadcrumb::generate();

		$this->theme->set_theme("default");
		$this->theme->set_layout("column3");

		return $this->theme->render('products::requirements',$data);
			

	}

	public  function get_detail($slug,$pID){

		$this->theme->set_layout("column2");

		$data['mode'] = "PRODUCTS";
		$data['title'] = 'Detail View';
		
		$data['product'] = Products::find($pID);
		$data['company'] = Post::find($data['product']->post_id);

		
		//--Meta Title--//
		
		$this->theme->title($data['product']->title.' - '.Settings::get('en','site_title'));
		
		//--BREADCRUMB--//
		Breadcrumb::addbreadcrumb('Home', URL::base());
		Breadcrumb::addbreadcrumb($data['product']->title, URL::base());
		Breadcrumb::setSeparator('&raquo;');
		$data['breadcrumb'] = Breadcrumb::generate();
		
		$data['map'] = null;
		return $this->theme->render('products::detailview',$data);
	}
	
	public function post_sendenquiry(){
			
		$rules = array(
				'pro_enq_name' => 'required',
				'pro_enq_email' => 'required|email',
				'pro_enq_contactno' => 'required',
				'selectbox-mylocation7' => 'required',
				'pro_enq_description' => 'required|min:25',
				
		);
			
		$v = Validator::make(Input::all(), $rules);
			
		if ($v->fails()) {
			$response = array(
					'status' => 'Fail',
					'message' => '<span class="text text-danger">Invalid Input..</span>',
			);
		} else {
			
			$loca = Input::get('selectbox-mylocation7');
			
			$loca = Locations::where('id','=',$loca)->first();
			
			$loca = $loca->name;
			
			$emailTemp = DB::table('emailtemplate')->where('variable','=','products_enquiry')->first();
			
			
			$temTitle = $emailTemp->title;
			$temDesc = $emailTemp->description;
			
			$productID = Input::get('product_id');
			
			$productTitle = Products::where('id','=',$productID)->first()->title;
			
			$producEmail = Products::where('id','=',$productID)->first()->email;
			
			$producttUrl = Input::get('product_url');
			
			$webTitle = Settings::get('en','site_title');
			$body = array(
					'product_title' => "<a href='".$producttUrl."'>$productTitle</a>",
					'website_title' => "<a href='".URL::base()."'>$webTitle</a>",
					'name' => trim(Input::get('pro_enq_name')),
					'email' => trim(Input::get('pro_enq_email')),
					'contact_no' => trim(Input::get('pro_enq_contactno')),
					'location' => $loca,
					'content' => Input::get('pro_enq_description'),
			);
			
			
			$footer = Settings::get('en','mail_smtp_footer');
			
			
			$description = Parser::parse_string($temDesc, $body,TRUE);
			
			$description .= "<p>$footer</p>";
				
			$p = array(
					'from' => trim(Input::get('pro_enq_email')),
					'to' => trim(Input::get('company_email')),
					'sender_name' => trim(Input::get('pro_enq_name')),
					'reply_to' => 'noreply@gmail.com',
					'subject' => trim($temTitle),
					'body' => trim($description),
			
			);
			
			//dd($p);
			Commoncall::mail($p);
				
					
				$response = array(
						'status' => 'Success',
						'message' => '<span class="text text-info">Thanks! Enquiry Sent...</span>',
				);
					
				//--send mail to Business Owner --//
					
		//	} else {
		//		$response = array(
		//				'status' => 'Fail',
		//				'message' => '<span class="text text-danger">Ah! something went wrong..</span>',
		//		);
		//	}
		}
			
		return Response::json($response);
			
	}
	
	public  function get_reply($slug,$pID){
	
		$this->theme->set_layout("column2");
	
		$data['mode'] = "LEAD";
		$data['title'] = 'Detail View';
	
		$data['buylead'] = DB::table('postrequirement')->find($pID);
		
		//--Meta Title--//
	
		$this->theme->title($data['buylead']->name.' - '.Settings::get('en','site_title'));
	
		//--BREADCRUMB--//
		Breadcrumb::addbreadcrumb('Home', URL::base());
		Breadcrumb::addbreadcrumb('Reply to '. $data['buylead']->name, URL::base());
		Breadcrumb::setSeparator('&raquo;');
		$data['breadcrumb'] = Breadcrumb::generate();
	
		$data['map'] = null;
		return $this->theme->render('products::leadview',$data);
	}
	
}

